package com.example.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component//该工具类不属于三层架构，用该注释将其对象存入IOC容器
public class AliOSSUtils {
    /**
     * @Value注解通常用于外部配置的属性注入，具体用法为:@Value("${配置文件中的key)")
     * 适用于属性较少且不复用的情况
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    */
    //通过@ConfigurationProperties注释进行属性注入
    @Autowired
    private AliOSSProperties aliOSSProperties;
    /**
     * 实现上传图片到OSS
     */

    public String upload(MultipartFile file) throws IOException {
        //通过get()方法得到每一个对应的值
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName =
                //随机名称   拼接
                UUID.randomUUID() +
                //截取原始文件名的后缀
                originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        /* endpoint  = oss-cn-beijing.aliyuncs.com

        https://javaweb-tails.oss-cn-beijing.aliyuncs.com/6175bfaa-5299-4e00-848a-e5bfa4dbdebf.jpg
         */
        //文件访问路径,字符串拼接上传到Oss图片的url地址
        String url = endpoint.split("//")[0]
                + "//"
                + bucketName
                + "."
                + endpoint.split("//")[1]
                + "/"
                + fileName;
        // 关闭ossClient
        ossClient.shutdown();

        return url;// 把上传到oss的路径返回
    }

}
